package cn.com.nes.common.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;

/**处理用户密码的工具类
 * @author yueb
 * @date 2018-11-17 11:23
 */
public class PasswordHandleUtil {

    /**
     *时间恒定判断密码
     * @param validatePassword 要验证密码
     * @param realPassword 实际密码
     * @return
     */
    public static boolean checkPassword(String validatePassword,String realPassword){

        byte[] a = validatePassword.getBytes();
        byte[] b = realPassword.getBytes();

        int diff = a.length ^ b.length;
        for(int i = 0; i < a.length && i < b.length; i++) {
            diff |= a[i] ^ b[i];
        }
        return diff == 0;
    }

    /**
     * 生成随机salt
     * @return salt
     */
    public static String buildSalt(){
        return RandomUtil.randomString(8);
    }

    /**
     * 生成加密密码
     * @param password 明文密码
     * @param salt 盐
     * @return
     */
    public static String buildEncryptPassword(String password,String salt){

        Digester md5 = new Digester(DigestAlgorithm.SHA256);

        String encryptPassword = md5.digestHex(password);

        return md5.digestHex(encryptPassword+salt);

    }

//    /**
//     * 判断密码是否正确
//     * @param passwordDto
//     * @param password
//     * @return
//     */
//    public static boolean verificationPassword(PasswordDto passwordDto,String password){
//        if(passwordDto!=null) {
//            //加密当前明文密码
//            String salt = passwordDto.getSalt();
//            //获取当前明文密码的加密后密码
//            String validatePassword = PasswordHandleUtil.buildEncryptPassword(password, salt);
//            //获取真实加密密码
//            String realPassword = passwordDto.getPassword();
//            return checkPassword(validatePassword, realPassword);
//        }else{
//            return false;
//        }
//    }


    public static void main(String[] args) throws Exception {

        String salt = "g87lkn5h";
        String pass = buildEncryptPassword("zxcvbnm", salt);

        System.out.println(salt + "================"+ pass);
    }

}
